﻿using System;
using System.Net;
using System.Xml.Linq;
using tnet.Model;
using Microsoft.Phone.Controls;
using tnet.Controls.Lookless;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace tnet
{
    public partial class MainPage : PhoneApplicationPage
    {
        private String ExtractImgFromHTML(String InputValue)
        {
            String[] TempArray = Regex.Split(InputValue, "<img");

            try
            {
                if (TempArray.Length > 1)
                {
                    InputValue = TempArray[1];
                    String[] TempArray2 = Regex.Split(InputValue, "src=\"");
                    InputValue = TempArray2[1];
                    InputValue = InputValue.Split('"')[0];
                }
                else
                {
                    InputValue = "";
                }
            }
            catch (Exception)
            {
                InputValue = "";
            }

            return InputValue;
        }

        /// <summary>
        /// process the blaze rss information
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        private void ResponseHandler(object Sender, DownloadStringCompletedEventArgs e)
        {

            String CurrentParseDate = String.Empty;
            String LastDateValue = Tools.GetSetting("LastDateValue");
            DateTime LastDate = new DateTime();
            if (!(String.IsNullOrEmpty(LastDateValue)))
            {
                LastDate = DateTime.Parse(LastDateValue);
            }

            #region // xml processing 

            XElement _xml;
            System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
            try
            {
                if (!e.Cancelled)
                {
                    _xml = XElement.Parse(e.Result);

                    Boolean FirstTime = true;
                    Boolean SecondTime = false;
                    Boolean ThirdTime = false;

                    foreach (XElement value in _xml.Elements("channel"))
                    {
                        // getdate this data was published 'pubDate'
                        try
                        {
                            CurrentParseDate = Tools.ScrubDate(value.Element("lastBuildDate").Value, " +0000"); 
                        }
                        catch (Exception)
                        {
                            CurrentParseDate = value.Element("pubDate").Value;
                        }
                         
                        DateTime CurrrentDate = DateTime.Parse(CurrentParseDate);

                        if (LastDateValue == CurrentParseDate)
                        {
                            ClosePreloader();
                            return;
                        }
                        else
                        {
                            if (FirstTime || BlogLstBx.Items.Count > 0)
                            {
                                BlogLstBx.Items.Clear();
                            }
                        }

                        foreach (XElement value2 in value.Elements("item"))
                        {
                            RssItem _RssItem = new RssItem();
                            _RssItem.Title = value2.Element("title").Value;
                            _RssItem.Link = value2.Element("link").Value;
                            _RssItem.Img = ExtractImgFromHTML(value2.Element("description").Value);
                            _RssItem.Description = value2.Element("description").Value;

                            #region // load 3 box's
                             
                            if (ThirdTime)
                            {
                                ThirdTime = false;

                                ThirdItemTxt.Text = BoxTextClip(_RssItem.Title);
                                ThirdItemTxt.Tag = _RssItem.FreezeDried;
                                FavBox3.Tag = _RssItem.FreezeDried;
                                HomeBox3.Tag = _RssItem.FreezeDried;
                                EmailBox3.Tag = _RssItem.FreezeDried;
                                TwitterBox3.Tag = _RssItem.FreezeDried;
                                FacebookBox3.Tag = _RssItem.FreezeDried;

                                Tools.SaveSetting("_Box3Name", ThirdItemTxt.Text);
                                Tools.SaveSetting("_Box3URL", _RssItem.FreezeDried); 

                            }
                            if (SecondTime)
                            {
                                SecondTime = false;
                                ThirdTime = true;

                                NextNewsTxt.Text = BoxTextClip(_RssItem.Title);
                                NextNewsTxt.Tag = _RssItem.FreezeDried;
                                FavBox2.Tag = _RssItem.FreezeDried;
                                HomeBox2.Tag = _RssItem.FreezeDried;
                                EmailBox2.Tag = _RssItem.FreezeDried;
                                TwitterBox2.Tag = _RssItem.FreezeDried;
                                FacebookBox2.Tag = _RssItem.FreezeDried;

                                Tools.SaveSetting("_Box2Name", NextNewsTxt.Text);
                                Tools.SaveSetting("_Box2URL", _RssItem.FreezeDried); 
                            }

                            if (FirstTime)
                            {
                                FirstTime = false;
                                SecondTime = true;
                                TopNewsItem.Text = BoxTextClip(_RssItem.Title);
                                TopNewsItem.Tag = _RssItem.FreezeDried;
                                FavBox1.Tag = _RssItem.FreezeDried;
                                HomeBox1.Tag = _RssItem.FreezeDried;
                                EmailBox1.Tag = _RssItem.FreezeDried;
                                TwitterBox1.Tag = _RssItem.FreezeDried;
                                FacebookBox1.Tag = _RssItem.FreezeDried;

                                Tools.SaveSetting("_Box1Name", TopNewsItem.Text);
                                Tools.SaveSetting("_Box1URL", _RssItem.FreezeDried); 
                            }

                            #endregion

                            BlogLstBx.Items.Add(_RssItem);
                        }
                    }
                }

                Tools.SaveSetting("LastDateValue", CurrentParseDate); 
                Tools.SaveSetting("LastDateResults.xml", e.Result);
            }
            catch
            {
                // Ignore Errors
            }

            #endregion 

            //// twitter rss...
            //WebClient TwitterClient2 = new WebClient();
            //TwitterClient2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ResponseHandler2);
            //TwitterClient2.DownloadStringAsync(new Uri(_TwitterRSS));

            ClosePreloader();
        } 
         
        private void ClosePreloader()
        {
            PreloadProcessingGrid.Visibility = Visibility.Collapsed;
            ApplicationBar.IsVisible = true;
        }
    }
}
